package com.wxy.netty.byteBuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;

import java.nio.charset.Charset;

/**
 * 关于ByteBuf内存释放问题：
 * 谁最后处理ByteBuf谁释放 byteBuf.release()
 * @author 47868
 */
public class ByteBufTest {

    public static void printByteBuf(ByteBuf byteBuf){
        while (byteBuf.readableBytes() > 0) {
            System.out.print(byteBuf.readByte()+" ");
        }
    }

    public static void slice(){
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        byteBuf.writeBytes(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
        ByteBuf byteBuf1 = byteBuf.slice(0,5);  //切片不允许写操作
        byteBuf1.retain();
        ByteBuf byteBuf2 = byteBuf.slice(5,5);
        byteBuf2.retain();
        System.out.println("byteBuf1: ");
        while (byteBuf1.readableBytes() > 0) {
            System.out.print(byteBuf1.readByte());
        }
        byteBuf1.release();
        System.out.println("\nbyteBuf2: ");
        printByteBuf(byteBuf2);
        byteBuf2.release();
    }

    public static void slice2(){
        ByteBuf leftByteBuf = ByteBufAllocator.DEFAULT.buffer();
        leftByteBuf.writeBytes(new byte[]{1, 2, 3, 4, 5});
        ByteBuf rightByteBuf = ByteBufAllocator.DEFAULT.buffer();
        rightByteBuf.writeBytes(new byte[]{6,7,8,9,10});
        //将两个切片拼接为一个
        /*ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
        byteBuf.writeBytes(leftByteBuf).writeBytes(rightByteBuf);
        printByteBuf(byteBuf);*/

        CompositeByteBuf compositeByteBuf = ByteBufAllocator.DEFAULT.compositeBuffer();
        compositeByteBuf.addComponents(true, leftByteBuf, rightByteBuf);
        printByteBuf(compositeByteBuf);
    }

     public static void main(String[] args) {
         ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();
         byteBuf.writeBytes(new byte[]{1,2,3});
         byteBuf.writeCharSequence("hello", Charset.defaultCharset());
         //使用get方法获取元素 指针不发生变化
         System.out.println(byteBuf.getByte(0));
         System.out.println(byteBuf.readByte());    //1
         //打标记
         byteBuf.markReaderIndex();
         System.out.println(byteBuf.readByte());    //2
         System.out.println(byteBuf.readByte());    //3
         //返回标记处
         byteBuf.resetReaderIndex();
         System.out.println(byteBuf.readByte());    //2
         System.out.println(byteBuf.readByte());    //3
         System.out.println(byteBuf);
         printByteBuf(byteBuf);
         System.out.println();
         //slice();
         slice2();
     }
}
